package com.vinoxm.rss.subscribe.handler;

import com.alibaba.fastjson.JSONException;
import com.vinoxm.common.utils.StringUtils;
import com.vinoxm.rss.subscribe.vo.SubscribeBase;
import com.vinoxm.rss.subscribe.vo.SubscribeSingleVo;
import com.vinoxm.rss.subscribe.vo.SubscribeVo;
import com.vinoxm.rss.model.RssResult;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class DefaultSubscribeHandler extends AbstractSubscribeHandler {

    private String regex;

    private DefaultSubscribeHandler() { }

    public DefaultSubscribeHandler(String regex) {
        this.regex = regex;
    }

    @Override
    protected String getUrlRegex() {
        return this.regex;
    }

    @Override
    protected SubscribeBase convertJsonToRssVo(JSONObject json) {
        SubscribeBase rssVo;
        try {
            rssVo = com.alibaba.fastjson.JSONObject.parseObject(json.toString()).toJavaObject(SubscribeVo.class);
        } catch (JSONException e) {
            rssVo = com.alibaba.fastjson.JSONObject.parseObject(json.toString()).toJavaObject(SubscribeSingleVo.class);
        }
        return rssVo;
    }

    @Override
    protected List<RssResult> getRssItems(SubscribeBase rssVo, Long pid, String regexStr) {
        ArrayList<RssResult> list = new ArrayList<>();
        if (rssVo instanceof SubscribeVo) {
            SubscribeBase.Rss rss = ((SubscribeVo) rssVo).getRss();
            if (null == rss) return emptyResultList();
            SubscribeBase.Channel channel = rss.getChannel();
            if (null == channel) return emptyResultList();
            List<SubscribeBase.Item> items = channel.getItem();
            if (null == items) return emptyResultList();
            if (StringUtils.isEmpty(regexStr)) {
                for (SubscribeBase.Item item : items) {
                    list.add(new RssResult(pid, item.getTitle(), item.getEnclosure().getUrl(), item.getPubDate()));
                }
            } else {
                String[] regex = regexStr.split(",");
                for (SubscribeBase.Item item : items) {
                    if (SubscribeBase.checkRegex(regex, item)) {
                        list.add(new RssResult(pid, item.getTitle(), item.getEnclosure().getUrl(), item.getPubDate()));
                    }
                }
            }
        }
        return list;
    }

}
